#include "tablecolumnlist.h"

#include "tablecolumn.h"

TableColumnList::~TableColumnList()
{
    if(columns != NULL){
        for(unsigned int i=0; i<columns->size(); i++) delete columns->at(i);
        delete columns; columns = NULL;
    }
}

TableColumnList::TableColumnList(const TableColumnList& other)
{
    if(other.columns == NULL) this->columns = NULL;
    else{
        columns = new vector<TableColumn *>();
        for(unsigned int i=0; i<other.columns->size(); i++) {
            TableColumn * c = other.columns->at(i)->clone();
            columns->push_back(c);
        }// for
    }// if-else
}

TableColumnList::TableColumnList(vector<TableColumn *> * columns)
{
    if(columns == NULL) this->columns = NULL;
    else{
        this->columns = new vector<TableColumn *>();
        for(unsigned int i=0; i<columns->size(); i++) {
            TableColumn * c = columns->at(i)->clone();
            this->columns->push_back(c);
        }// for
    }// if-else
}

int TableColumnList::size()
{
    return columns->size();
}

void TableColumnList::addColumn(TableColumn * column)
{
    if(columns == NULL) columns = new vector<TableColumn *>();
    if(column != NULL) columns->push_back(column->clone());
}

void TableColumnList::addColumn(const string & name, TableColumnType type)
{
    if(columns == NULL) columns = new vector<TableColumn *>();
    columns->push_back(new TableColumn(type,name));
}

vector<TableColumn *> * TableColumnList::getColumns() const
{
    return columns;
}

void TableColumnList::setColumns(vector<TableColumn *> * columns)
{
    // clear the list
    if(this->columns != NULL){
        for(unsigned int i=0; i<this->columns->size(); i++) delete this->columns->at(i);
        delete this->columns; this->columns = NULL;
    }// if

    if(columns != NULL){
        this->columns = new vector<TableColumn *>();
        for(unsigned int i=0; i<columns->size(); i++) {
            TableColumn * c = columns->at(i)->clone();
            this->columns->push_back(c);
        }// for
    } //if
}

string TableColumnList::toString()
{
    string str = "<";
    if(columns != NULL){
        for(unsigned int i=0; i<columns->size(); i++){
            str = str + columns->at(i)->toString() + ",";
        }//for
        str.erase(str.length()-1);
    }//if
    str = str + ">";
    return str;
}

TableColumnType TableColumnList::getColumnType(const string & name)
{
    bool finded = false;
    unsigned int i = 0;

    if(columns != NULL){
        while(!finded && i<columns->size()){
            if(columns->at(i)->getName() == name) finded = true;
            i++;
        }//while
    }// if

    if(!finded){
		 TableColumnType t;
		 t.type = UNKNOWN_TYPE;
		 return t ;
	 }
    return columns->at(i-1)->getType();
}

TableColumnList * TableColumnList::clone()
{
    return new TableColumnList(*this);
}
